{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Ensemble learning using the voting classifier"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can find the accompanying article [here](https://levelup.gitconnected.com/ensemble-learning-using-the-voting-classifier-a28d450be64d)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setup"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from sklearn.datasets import make_classification, make_regression\n",
    "from sklearn.model_selection import train_test_split\n",
    "                                     \n",
    "from sklearn.metrics import accuracy_score\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "\n",
    "from sklearn.naive_bayes import GaussianNB\n",
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "from sklearn.tree import DecisionTreeClassifier\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "from sklearn.ensemble import VotingClassifier\n",
    "\n",
    "from collections import Counter"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Preparing the dataset for classification "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "X, y = make_classification(n_samples=500, \n",
    "                           n_features=10,\n",
    "                           random_state=42)\n",
    "\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, \n",
    "                                                    test_size=0.2, \n",
    "                                                    stratify=y, \n",
    "                                                    random_state=42)\n",
    "\n",
    "scaler = StandardScaler()\n",
    "X_train = scaler.fit_transform(X_train)\n",
    "X_test = scaler.transform(X_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Counter({1: 250, 0: 250})"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Counter(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Fitting the models"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "clf_list = [('decision tree', DecisionTreeClassifier()),\n",
    "            ('logistic regression', LogisticRegression()),\n",
    "            ('knn', KNeighborsClassifier()),\n",
    "            ('naive bayes classifier', GaussianNB())]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "decision tree's accuracy: 0.86\n",
      "logistic regression's accuracy: 0.85\n",
      "knn's accuracy: 0.86\n",
      "naive bayes classifier's accuracy: 0.87\n"
     ]
    }
   ],
   "source": [
    "for model_tuple in clf_list:\n",
    "    model = model_tuple[1]\n",
    "    if 'random_state' in model.get_params().keys():\n",
    "        model.set_params(random_state=42)\n",
    "    model.fit(X_train, y_train)\n",
    "    y_pred = model.predict(X_test)\n",
    "    acc = accuracy_score(y_pred, y_test)\n",
    "    print(f\"{model_tuple[0]}'s accuracy: {acc:.2f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Using the `VotingClassifier`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Voting Classifier's accuracy: 0.88\n"
     ]
    }
   ],
   "source": [
    "voting_clf = VotingClassifier(clf_list, voting='hard')\n",
    "voting_clf.fit(X_train, y_train)\n",
    "y_pred = voting_clf.predict(X_test)\n",
    "print(f\"Voting Classifier's accuracy: {accuracy_score(y_pred, y_test):.2f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Voting Classifier's accuracy: 0.85\n"
     ]
    }
   ],
   "source": [
    "voting_clf = VotingClassifier(clf_list, voting='soft')\n",
    "voting_clf.fit(X_train, y_train)\n",
    "y_pred = voting_clf.predict(X_test)\n",
    "print(f\"Voting Classifier's accuracy: {accuracy_score(y_pred, y_test):.2f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## BONUS: `VotingRegressor`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "# load the libraries \n",
    "\n",
    "from sklearn.datasets import make_regression\n",
    "                                     \n",
    "from sklearn.neighbors import KNeighborsRegressor\n",
    "from sklearn.tree import DecisionTreeRegressor\n",
    "from sklearn.linear_model import LinearRegression\n",
    "from sklearn.ensemble import VotingRegressor\n",
    "\n",
    "from sklearn.metrics import mean_squared_error\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "# prepare the dateset \n",
    "X, y = make_regression(n_samples=500, \n",
    "                       n_features=10,\n",
    "                       random_state=42)\n",
    "\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, \n",
    "                                                    test_size=0.2, \n",
    "                                                    random_state=42)\n",
    "\n",
    "scaler = StandardScaler()\n",
    "X_train = scaler.fit_transform(X_train)\n",
    "X_test = scaler.transform(X_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "# define the list of estimators \n",
    "est_list = [('decision tree', DecisionTreeRegressor()),\n",
    "            ('linear regression', LinearRegression()),\n",
    "            ('knn', KNeighborsRegressor())\n",
    "            ]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "decision tree's MSE: 10651.04\n",
      "linear regression's MSE: 0.00\n",
      "knn's MSE: 4697.50\n"
     ]
    }
   ],
   "source": [
    "for model_tuple in est_list:\n",
    "    model = model_tuple[1]\n",
    "    if 'random_state' in model.get_params().keys():\n",
    "        model.set_params(random_state=42)\n",
    "    model.fit(X_train, y_train)\n",
    "    y_pred = model.predict(X_test)\n",
    "    mse = mean_squared_error(y_pred, y_test)\n",
    "    print(f\"{model_tuple[0]}'s MSE: {mse:.2f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Voting Classifier's accuracy: 2322.66\n"
     ]
    }
   ],
   "source": [
    "voting_reg = VotingRegressor(est_list)\n",
    "voting_reg.fit(X_train, y_train)\n",
    "y_pred = voting_reg.predict(X_test)\n",
    "print(f\"Voting Classifier's accuracy: {mean_squared_error(y_pred, y_test):.2f}\")"
   ]
  }
 ],
 "metadata": {
  "file_extension": ".py",
  "kernelspec": {
   "display_name": "Python 3.7.3 64-bit ('base': conda)",
   "language": "python",
   "name": "python37364bitbaseconda6b1679f558f347048f914ac332fcb241"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  },
  "mimetype": "text/x-python",
  "name": "python",
  "npconvert_exporter": "python",
  "pygments_lexer": "ipython3",
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": true
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  },
  "version": 3
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
